package cn.tlb.upload;

import android.app.ProgressDialog;
import android.content.ContentResolver;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;

import com.alexbbb.uploadservice.MultipartUploadRequest;
import com.alexbbb.uploadservice.UploadNotificationConfig;

import org.xutils.common.Callback;
import org.xutils.http.ProgressHandler;
import org.xutils.http.RequestParams;
import org.xutils.http.body.MultipartBody;
import org.xutils.view.annotation.Event;
import org.xutils.view.annotation.ViewInject;
import org.xutils.x;

import java.io.File;
import java.io.InputStream;
import java.net.URLConnection;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.UUID;

import cn.tlb.xutilsdownload.R;

public class UploadActivity extends AppCompatActivity {
    private static final String TAG = UploadActivity.class.getSimpleName();
    private static final int REQUEST_FOR_CONTENT = 100;
    private static final File ROOT = Environment.getExternalStorageDirectory();
    private static final String LOCAL_HOST = "http://192.168.47.146:8080/http/servlet/FileUploadServlet";
    private ArrayList<String> data = new ArrayList<>();

    @ViewInject(R.id.name_value) EditText nameValue;
    @ViewInject(R.id.filepath) EditText filepath;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_upload);
        x.view().inject(this);
    }

    @Event(R.id.filepath)
    private void onPickFileEvent(View v){

        Intent intent = new Intent();
        intent.setAction(Intent.ACTION_GET_CONTENT);
        intent.setDataAndType(Uri.fromFile(ROOT), "file/*");
        startActivityForResult(intent, REQUEST_FOR_CONTENT);
    }

    ///////////////////////////////////////////////////////////////////////////
    //TODO xUtils upload
    ///////////////////////////////////////////////////////////////////////////
    @Event(R.id.button11)
    private void onSubmit11Event(View v){
        //1. 请求参数, URL不能为空
        RequestParams params = new RequestParams(LOCAL_HOST);
        //2. 设置表单提交
        params.setMultipart(true);
        //3.2 添加表单项
        HashMap<String, Object> map = new HashMap<>();
        map.put("name1","张三");
        map.put("file1", new File(ROOT.getAbsolutePath() + "/cn.tlb/DecorView.java"));
        map.put("name2","李四");
        map.put("file2", new File(ROOT.getAbsolutePath() + "/cn.tlb/skin_424.png"));
        map.put("file3", new File(ROOT.getAbsolutePath() + "/Movies/1.mp4"));
        //3.1
        // 使用唯一的构造方法创建MultipartBody
        MultipartBody multipartBody = new MultipartBody(map, "utf-8");
        //3.3 设置upload进度回调接口, 这里没能看到进度值的打印,没用??
        multipartBody.setProgressHandler(new ProgressHandler() {
            @Override
            public boolean updateProgress(long total, long current, boolean forceUpdateUI) {
                Log.i(TAG, String.format("updateProgress(total=%ld, current=%ld, forceUpdateUI=%s)",
                        total, current, forceUpdateUI));
                return false;
            }
        });

        //3. 设置请求体 -- multipart类型使用 MultipartBody
        params.setRequestBody(multipartBody);

        Callback.Cancelable cancelable = x.http().post(params, new Callback.ProgressCallback<String>() {
            @Override
            public void onWaiting() {

            }

            @Override
            public void onStarted() {

            }

            @Override
            public void onLoading(long total, long current, boolean isDownloading) {

            }

            @Override
            public void onSuccess(String result) {
                Log.i(TAG, "onSuccess:  "+ result);
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                Log.i(TAG, "onError:  "+ ex);
            }

            @Override
            public void onCancelled(CancelledException cex) {

            }

            @Override
            public void onFinished() {
                Log.i(TAG, "onFinished");
            }
        });


    }




    ///////////////////////////////////////////////////////////////////////////
    //TODO 使用HttpURLConnection自定义上传
    ///////////////////////////////////////////////////////////////////////////

    public void cancel(View v){
        if(formUtil != null){
            formUtil.cancel();
        }

        new Thread(){
            @Override
            public void run() {
                new FormUtil();
            }
        }.start();
    }

    FormUtil formUtil;
    @Event(R.id.submit)
    private void onSubmitEvent(View v){

        //创建表单对象 <form action="http://www.baidu.com" method="POST"><input></form>
//        Form form = new Form("http://192.168.50.211:8135/test/uploadfile.php", "POST");
        Form form = new Form(LOCAL_HOST, "POST");
        //往表单中添加输入项 <input type="file", name="file1", value="ROOT.getAbsolutePath() + "/cn.tlb/DecorView.java"">
        form.inputs.add(Input.newTextInput("name1", "张飞关羽"));
        form.inputs.add(Input.newFileInput("resfile", ROOT.getAbsolutePath() + "/Movies/1.mp4"));
        form.inputs.add(Input.newTextInput("name2", "张飞关羽33333"));
        form.inputs.add(Input.newFileInput("file1", ROOT.getAbsolutePath() + "/cn.tlb/skin_424.png"));

        formUtil = new FormUtil();
        formUtil.uploadMultipartForm(form, new FormUtil.OnSubmitListener() {
            ProgressDialog progressDialog;

            @Override
            public void onStart() {
                progressDialog = new ProgressDialog(UploadActivity.this);
                progressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
                progressDialog.show();
            }

            @Override
            public void onError(Throwable th) {
                Toast.makeText(UploadActivity.this, th.getMessage(), Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onUploading(String absFilePath, long totalSize, long uploadSize, int progress) {
                Log.i(TAG, String.format("onUploading(absFilePath=%s, totalSize=%d, long uploadSize=%d, int progress=%d",
                        absFilePath, totalSize, uploadSize, progress));
                progressDialog.setProgress(progress);
            }

            @Override
            public void onCancel() {
                Toast.makeText(UploadActivity.this, "onCancel", Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onSuccess(String result) {
                Toast.makeText(UploadActivity.this, result, Toast.LENGTH_SHORT).show();
                Log.i(TAG, "onSuccess(" + result + ")");
            }

            @Override
            public void onFailed(int responseCode) {
                Toast.makeText(UploadActivity.this, "responseCode;" + responseCode, Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onFinish() {
                progressDialog.dismiss();
            }
        });

//        new AsyncTask<Void, Void, String>(){
//            final String BOUNDARY = "---------------------------7df1c314e08f2";
//            final String TWO_DASH = "--";
//            final String LINE_SEPARATOR = "\r\n";
//            @Override
//            protected String doInBackground(Void... params) {
//
//                try {
//                    URL url = new URL("http://192.168.47.146:8080/http/servlet/FileUploadServlet");
//                    HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
//                    urlConnection.setDoOutput(true);
//                    urlConnection.setUseCaches(false);
//                    urlConnection.setRequestMethod("POST");
//
//                    urlConnection.addRequestProperty("Content-Type", "multipart/form-data; boundary=" + BOUNDARY);
//
//                    DataOutputStream dos = new DataOutputStream(urlConnection.getOutputStream());
//                    dos.write(LINE_SEPARATOR.getBytes());
//
//                    dos.write((TWO_DASH + BOUNDARY).getBytes());
//                    dos.write(LINE_SEPARATOR.getBytes());
//                    dos.write("Content-Disposition: form-data; name=\"name\"".getBytes());
//                    dos.write(LINE_SEPARATOR.getBytes());
//                    dos.write(LINE_SEPARATOR.getBytes());
//                    dos.write("战三李四".getBytes("utf-8"));
//                    dos.write(LINE_SEPARATOR.getBytes());
//
//                    dos.write((TWO_DASH + BOUNDARY).getBytes());
//                    dos.write(LINE_SEPARATOR.getBytes());
//                    String path = ROOT.getAbsolutePath() + "/cn.tlb/DecorView.java";
//                    dos.write(("Content-Disposition: form-data; name=\"file\"; filename=\"" + path + "\"").getBytes());
//                    dos.write(LINE_SEPARATOR.getBytes());
//                    dos.write(("Content-Type: application/octet-stream").getBytes());
//                    dos.write(LINE_SEPARATOR.getBytes());
//                    dos.write(LINE_SEPARATOR.getBytes());
//                    FileInputStream in = new FileInputStream(path);
//                    byte[] bs = new byte[1024];
//                    int len;
//                    while((len = in.read(bs))!=-1) {
//                        dos.write(bs, 0, len);
//                    }
//                    in.close();
//                    dos.write(LINE_SEPARATOR.getBytes());
//                    dos.write((TWO_DASH + BOUNDARY + TWO_DASH + LINE_SEPARATOR).getBytes());
//                    dos.flush();
//                    dos.close();
//
//                    if(urlConnection.getResponseCode() == 200) {
//                        BufferedReader br = new BufferedReader(new InputStreamReader(urlConnection.getInputStream()));
//                        StringBuffer sb = new StringBuffer();
//                        String line;
//                        while((line = br.readLine())!=null){
//                            sb.append(line).append(LINE_SEPARATOR);
//                        }
//                        return sb.toString();
//                    }
//                } catch (Exception e) {
//                    e.printStackTrace();
//                }
//
//                return null;
//            }
//
//            @Override
//            protected void onPostExecute(String s) {
//                Toast.makeText(UploadActivity.this, s, Toast.LENGTH_SHORT).show();
//            }
//        }.execute();
    }

    ///////////////////////////////////////////////////////////////////////////
    //TODO https://github.com/alexbbb/android-upload-service
    //带Notification
    ///////////////////////////////////////////////////////////////////////////
    @Event(R.id.button12)
    private void onUpload(View v){
        final String uploadID = UUID.randomUUID().toString();
        final String serverUrlString = LOCAL_HOST;

        try {
            new MultipartUploadRequest(this, uploadID, serverUrlString)
                    .addFileToUpload(ROOT.getAbsolutePath() + "/Movies/1.mp4", "file1")
                    //.addHeader("your-custom-header-name", "your-custom-value")
                    .addParameter("your-param-name", "your-param-value")
                    .setNotificationConfig(new UploadNotificationConfig())
                    .setMaxRetries(2)
                    .startUpload();
        } catch (Exception exc) {
            Log.e("AndroidUploadService", exc.getMessage(), exc);
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if(requestCode == REQUEST_FOR_CONTENT){
            if(data != null){
                Uri uri = data.getData();
                Log.i(TAG, "data-->"+data);
                Log.i(TAG, "Uri-->"+uri);

                File file = new File(uri.getPath());
                Log.i(TAG, "file-->"+file);
                if(file!=null) {
                    Log.i(TAG, "file-->" + file.getAbsolutePath());
                    Log.i(TAG, "file-->" + URLConnection.guessContentTypeFromName(file.getAbsolutePath()));
                }

                ContentResolver resolver = getContentResolver();
                String type = resolver.getType(uri);
                Log.i(TAG, "type-->" + type);



                InputStream in = null;
                try {
                    in = resolver.openInputStream(uri);
                    String contentTypeFromStream = URLConnection.guessContentTypeFromStream(in);
                    Log.i(TAG, "contentTypeFromStream-->" + contentTypeFromStream);
                } catch (Exception e) {
                    e.printStackTrace();
                }


            }
        }
    }
}
